<?php

class Default_LoginController extends My_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
        parent::init();
    }


    public function indexAction()
    {
        $resource = $this->getRequest()->getParam('resource', 'admin');
        $auth = Zend_Auth::getInstance();
        if ($auth->hasIdentity())
        {
            $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
            $redirector->gotoSimple('index', 'index', $resource);
        }
        
        $loginForm = new Default_Form_Login();
        $this->view->form = $loginForm;

        if ($this->getRequest()->isPost())
        {
            $datosPost = $this->getRequest()->getPost();
            $loginForm->populate($datosPost);
            if ($loginForm->isValid($datosPost))
            {
                // Rutina de login...
                $userName = $loginForm->getValue('user');
                $pass = $loginForm->getValue('password');
                $authManager = Application_Model_AuthManager::getInstance();
                $estaAcreditado = $authManager->authorizedUser($userName, $pass);
                if (true == $estaAcreditado)
                {
                    // Cookie and redirect
                    @setcookie('rememberLogin-user', $userName, time()+3600, 'localhost');
                    @setcookie('rememberLogin-hash', md5($pass), time()+3600, 'localhost');
                    
                    $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
                    $redirector->gotoSimple('index', 'index', $resource);
                }
            }
        }
    }

    public function logoutAction()
    {
        Zend_Auth::getInstance()->clearIdentity();
        $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
        $redirector->gotoSimple('index', 'index', 'default');
    }

}

